import router from './router'
import store from './store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getUser, getToken, getPermission } from '@/utils/auth'

NProgress.configure({ showSpinner: false })

// 是否有权限判断
function hasPermission(perms, permissions) {
  if (perms.indexOf('*') >= 0) return true // 超级管理员角色所有权限
  if (!permissions) return true
  return perms.some(perm => permissions.indexOf(perm) >= 0)
}

const whiteList = ['/login', '/auth-redirect'] // URL白名单直接放行访问
router.beforeEach((to, from, next) => {
  NProgress.start()
  const token = getToken()
  const user = getUser()
  if (token && user) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      const perms = getPermission()
      if (store.getters.dynamicRouters.length === 0) {
        // 根据perms权限生成可访问的路由表
        store.dispatch('GenerateRoutes', { perms }).then(() => {
          router.addRoutes(store.getters.dynamicRouters) // 动态添加可访问路由表
        })
      }
      if (hasPermission(perms, to.meta.perms)) {
        next()
      } else {
        next({ path: '/401', replace: true, query: { noGoBack: true }})
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
